package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"goods_svc/models/cache"
	"goods_svc/models/mysql"
	"time"

	"goods_svc/goods"
	"goods_svc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopShowLogic {
	return &ShopShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品详情
func (l *ShopShowLogic) ShopShow(in *goods.ShopShowRequest) (*goods.ShopShowResponse, error) {
	// todo: add your logic here and delete this line

	//去mysql数据库查一下
	var shops mysql.Shop
	mysql.DB.Debug().Where("id = ?", in.Id).Find(&shops)

	//使用缓存
	key := fmt.Sprintf("shop_show_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &shops)
	} else {
		marshal, _ := json.Marshal(shops)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	}

	//实现详情
	return &goods.ShopShowResponse{
		UserId: int64(shops.UserId),
		Name:   shops.Name,
		Price:  float32(shops.Price),
		Stock:  int64(shops.Stock),
	}, nil
}
